<script>
	import globalConfig from "config";

	global.isLogin = function() {
		try {
			var token = uni.getStorageSync("token");
			// var token = "20793f3e5cbc4e64a7955f7f445b65e5"; //redis写死测试用的
		} catch (e) {
			//TODO handle the exception
			return false;
		}
		if (token == "" || token == null) {
			return false;
		} else {
			return token;
		}
	};

	global.loginByCode = function(afterLoginCall = null) {
		wx.login({
			success: function(res) {
				if (res.code) {
					global.setWxCode(res.code);
					//请求注册接口
					uni.request({
						method: "POST",
						url: globalConfig.API_HOST + "/app/user/auth/wxMpLogin", //仅为示例，并非真实接口地址。
						header: {
							token: global.isLogin(),
						},
						data: {
							code: res.code,
							apiVersion: globalConfig.API_VERSION,
						},
						success: (res) => {
							if (res.data.code === 0) {
								global.setToken(res.data.data.token);
								if (afterLoginCall) {
									afterLoginCall();
								}
							} else if (res.data.code == 1) {
								//没注册过的用户
								uni.setStorage({
									key: "wx_token",
									data: res.data.data.token,
									success: function() {
										//console.log('success');
									},
								});
							}
						},
					});
				} else {}
			},
		});
	};

	global.setToken = function(token) {
		uni.setStorageSync("token", token);
		console.log("what");
		console.log(token);
		/*
		uni.setStorage({
			key: 'token',
			data: token,
			success: function () {
				//console.log('success');
			}
		});
		*/
	};

	global.getWxCode = function() {
		try {
			var wxCode = uni.getStorageSync("wxCode");
		} catch (e) {
			//TODO handle the exception
			return false;
		}
		if (wxCode == "" || wxCode == null) {
			return false;
		} else {
			return wxCode;
		}
	};

	global.setWxCode = function(wxCode) {
		uni.setStorage({
			key: "wxCode",
			data: wxCode,
			success: function() {
				//console.log('success');
			},
		});
	};

	export default {
		onLaunch: function() {
			console.log("App Launch");
		},
		onShow: function() {
			console.log("App Show");
		},
		onHide: function() {
			console.log("App Hide");
		},
	};
</script>

<style>
	/*每个页面公共css */
	page {
		background: #f5f5f5;
	}
</style>
